using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement.Billing;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement.Billing
{
    /// <summary>
    /// 获取开票通知单列表查询处理器
    /// </summary>
    public class GetBillingNoticeListHandler : IRequestHandler<GetBillingNoticeListCommand, APIResult<GetBillingNoticeListDto>>
    {
        private readonly RBACDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public GetBillingNoticeListHandler(RBACDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 处理获取开票通知单列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>开票通知单列表结果</returns>
        public async Task<APIResult<GetBillingNoticeListDto>> Handle(GetBillingNoticeListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建基础查询
                var query = _dbContext.Set<BillingAccounting>()
                    .Where(b => !b.IsDeleted)
                    .Include(b => b.BillingMaterials)
                    .AsQueryable();

                // 应用搜索条件
                if (!string.IsNullOrWhiteSpace(request.BillNo))
                {
                    query = query.Where(b => b.BillNumber != null && b.BillNumber.Contains(request.BillNo));
                }

                if (!string.IsNullOrWhiteSpace(request.CustomerName))
                {
                    query = query.Where(b => b.CustomerName != null && b.CustomerName.Contains(request.CustomerName));
                }

                if (!string.IsNullOrWhiteSpace(request.InvoiceName))
                {
                    query = query.Where(b => b.BillingMaterials != null &&
                        b.BillingMaterials.Any(m => m.InvoiceName != null && m.InvoiceName.Contains(request.InvoiceName)));
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(b => b.BillDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    query = query.Where(b => b.BillDate <= request.EndDate.Value.Date.AddDays(1).AddTicks(-1));
                }

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页查询
                var billingAccounts = await query
                    .OrderByDescending(b => b.CreateTime)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 转换为DTO
                var billingNoticeDtos = new List<BillingNoticeDto>();
                foreach (var billing in billingAccounts)
                {
                    var dto = new BillingNoticeDto
                    {
                        Id = billing.Id,
                        BillNumber = billing.BillNumber,
                        BusinessType = billing.BusinessType,
                        CustomerName = billing.CustomerName ?? "",
                        CustomerCode = billing.CustomerName ?? "",
                        BankName = billing.BankName,
                        DeliveryEmail = billing.DeliveryEmail,
                        BillDate = billing.BillDate,
                        Operator = billing.Operator,
                        InvoiceType = billing.InvoiceType,
                        ProductCode = billing.ProductCode,
                        RedReason = billing.RedReason,
                        Remarks = billing.Remarks,
                        BillStatus = billing.BillStatus,
                        Reviewer = billing.Reviewer,
                        TaxRate = billing.TaxRate,
                        TaxId = billing.TaxId,
                        BusinessStatus = billing.BusinessStatus,
                        ReviewDate = billing.ReviewDate,
                        InvoiceCategory = billing.InvoiceCategory,
                        AddressPhone = billing.AddressPhone,
                        Status = billing.Status,
                        BillingMaterials = new List<BillingMaterialDto>()
                    };

                    // 处理物料明细
                    if (billing.BillingMaterials != null)
                    {
                        foreach (var material in billing.BillingMaterials)
                        {
                            var materialDto = new BillingMaterialDto
                            {
                                OrderNumber = material.OrderNumber,
                                MaterialCode = material.MaterialCode,
                                MaterialName = material.MaterialName,
                                Unit = material.Unit,
                                Quantity = material.Quantity,
                                UnitPrice = material.UnitPrice,
                                Amount = material.Amount,
                                InvoiceName = material.InvoiceName,
                                Remarks = material.Remarks,
                                Specification = "" // 假设规格型号为空，实际应根据业务调整
                            };
                            dto.BillingMaterials.Add(materialDto);
                        }

                        // 计算合计金额
                        dto.TotalAmount = dto.BillingMaterials.Sum(m => m.Amount ?? 0);
                    }

                    billingNoticeDtos.Add(dto);
                }

                var result = new GetBillingNoticeListDto
                {
                    PageDatas = billingNoticeDtos,
                    TotalCount = totalCount
                };

                return new APIResult<GetBillingNoticeListDto>
                {
                    Code = APIEnums.Success,
                    Msg = "获取开票通知单列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new APIResult<GetBillingNoticeListDto>
                {
                    Code = APIEnums.Fail,
                    Msg = "获取开票通知单列表失败：" + ex.Message,
                    Data = new GetBillingNoticeListDto()
                };
            }
        }
    }
}